// tools/scripts/check-ports.js
import { execSync } from 'child_process';
import { promisify } from 'util';
import net from 'net';

const ports = [3000, 5001, 5002, 5003, 5004, 3001];
const timeout = 1000;

async function checkPort(port) {
  return new Promise((resolve) => {
    const socket = new net.Socket();
    
    socket.setTimeout(timeout);
    socket.on('connect', () => {
      socket.destroy();
      resolve(true);
    });
    
    socket.on('timeout', () => {
      socket.destroy();
      resolve(false);
    });
    
    socket.on('error', () => {
      resolve(false);
    });
    
    socket.connect(port, 'localhost');
  });
}

async function checkAllPorts() {
  console.log('🔍 检查端口占用情况...\n');
  
  const results = await Promise.all(
    ports.map(async (port) => {
      const isOccupied = await checkPort(port);
      return { port, isOccupied };
    })
  );
  
  results.forEach(({ port, isOccupied }) => {
    const status = isOccupied ? '❌ 占用' : '✅ 空闲';
    console.log(`端口 ${port}: ${status}`);
  });
  
  const occupiedPorts = results.filter(r => r.isOccupied).map(r => r.port);
  if (occupiedPorts.length > 0) {
    console.log(`\n⚠️  以下端口被占用: ${occupiedPorts.join(', ')}`);
    console.log('💡 建议运行: npm run dev:kill-ports');
  } else {
    console.log('\n🎉 所有端口都可用！');
  }
}

checkAllPorts().catch(console.error);